package com.ytktt.study.week3.task346.gateway.router;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * TODO
 *
 * @author ytk
 */
public class WeightHttpEndpointRouter implements HttpEndpointRouter {

    private final Map<String, Integer> weightMapping;
    private final Random random = new Random();

    public WeightHttpEndpointRouter(Map<String, Integer> weightMapping) {
        this.weightMapping = weightMapping;
    }

    @Override
    public String route(List<String> endpoints) {
        List<String> repeatEndpoints = new ArrayList<>();
        for (String endpoint : endpoints) {
            for (int i = 0; i < this.weightMapping.get(endpoint); i++) {
                repeatEndpoints.add(endpoint);
            }
        }
        int size = repeatEndpoints.size();
        return repeatEndpoints.get(this.random.nextInt(size));
    }
}
